import { Table } from '@tanstack/react-table'
import { X } from 'lucide-react'

import { Button } from '@renderer/components/ui/button'
import { Input } from '@renderer/components/ui/input'
import { DataTableViewOptions } from '@renderer/components/table/data-table-view-options'
import { DrawerTrigger } from '@renderer/components/ui/drawer'
import usePluginLocalStore from '@renderer/store/plugin-local'
import { useShallow } from 'zustand/react/shallow'

interface DataTableToolbarProps<TData> {
  table: Table<TData>
}

export function DataTableToolbar<TData>({ table }: DataTableToolbarProps<TData>) {
  const isFiltered = table.getState().columnFilters.length > 0
  const { editForm, setDrater } = usePluginLocalStore(
    useShallow((state) => ({
      editForm: state.editForm,
      setDrater: state.setDrater
    }))
  )

  return (
    <div className="flex items-center justify-between">
      <div className="flex flex-1 items-center gap-2">
        <Input
          placeholder="过滤名称..."
          value={(table.getColumn('name')?.getFilterValue() as string) ?? ''}
          onChange={(event) => table.getColumn('name')?.setFilterValue(event.target.value)}
          className="h-8 w-[150px] lg:w-[250px]"
        />
        {isFiltered && (
          <Button variant="ghost" size="sm" onClick={() => table.resetColumnFilters()}>
            Reset
            <X />
          </Button>
        )}
      </div>
      <div className="flex items-center gap-2">
        <DataTableViewOptions table={table} />
        <DrawerTrigger asChild>
          <Button
            variant="outline"
            onClick={() => {
              editForm('add')
              setDrater('plugin', true)
            }}
          >
            添加
          </Button>
        </DrawerTrigger>
      </div>
    </div>
  )
}
